<template>
  <div class="container">
    <!-- 顶部 -->
    <div class="title-wrap">
      <div class="title-text">
        <img src="../../assets/img/recognize_icon.png" alt="" />
        <span>科普识图</span>
      </div>
      <!-- 最小最大关闭 -->
      <div class="title-btns">
        <img src="../../assets/img/mini-w.png" @click="windowMin" alt="" />
        <img src="../../assets/img/close-w.png" @click="windowClose" alt="" />
      </div>
    </div>
    <div class="content">
        <div class="left_wrap">
            <div style="display:flex;align-items:center;margin: 100px 0  0 0;">
                <img width="25px" src="../../assets/img/tips_icon.png" alt="">
                <span style="margin-left:10px">支持识别PNG、JPG、JPEG、BMP格式图片。</span>
            </div>
            <div class="img_container" >
                <img v-if="empty" class="empty_img" src="../../assets/img/emptyUpload.png" alt="">
                <img class="uploadImage" :src="uploadImage" alt="">
                <div class="select_box">
                </div>
                <div class="checkList">
                  <div v-for="(item) in checkList" :key="item.id" >
                    <el-radio style="margin: 10px 20px 0px 20px;" v-model="selectClass" :label="item" >{{item.name}}</el-radio>
                  </div>
                </div>
                
            </div>
            <div v-if="frame" class="frame">
            </div>
            <div v-if="scan" class="img_mask">
            </div>
            <div style="position:relative">
                <div v-if="showCode" class="qrcode-box">
                    <img  :src="qrImage" alt="" />
                    <div style="color:#000000;font-size:14px;">微信扫码传图</div>
                    <!-- <button class="up_btn" style="position:absolute;bottom:0px;border-radius: 30px ;" @click="showCode = false">手机上传</button> -->
                </div>
                
            </div>
            <div class="btn_wrap">
                <div style="display:flex">
                    <button class="up_btn uploadByPhone"  style="border-radius: 30px;" @click="Telupload">手机上传</button>
                    <el-upload
                        class="upload"
                        list-type="picture"
                        action="https://upload.qiniup.com"
                        ref="upImg"
                        :limit="1"
                        :show-file-list="false"
                        accept=".jpg , .png , .jpeg , .bmp"
                        :before-upload="beforeUpload"
                        >
                        <button class="up_btn" style=" margin-left: 40px;border-radius: 30px;" @click="localUpload">本地导入
                        </button>
                    </el-upload>
                </div>
                <div>
                    <button class="recognize" @click="handleRecoginze">开始识别</button>
                </div>
            </div>
        </div>
        <div class="right_wrap">
            <div class="result-box">
                <div class="result_title">
                    <div style="text-align: center;padding-top:8px">
                        <span style="color:#333333;font-size:18px">识别结果</span>
                    </div>
                    <div class="result-bg">
                        <div :class="[recognizeResult.length>3 ? 'recognizeResults' : 'recognizeResult']" v-if="animation" >
                          <div v-for="(item) in recognizeResult" :key="item.index"  style="margin: 10px 35px;">
                              <div style="display:flex;justify-content:center;margin-top:50px" v-if="item.name.indexOf('非植物')!== -1 ||  item.name.indexOf('非动物')!== -1">{{item.name}}</div>
                              <div v-else >
                                  <div style="display:flex;position:relative;font-size:18px;width:402px;height:31px;line-height:36px">
                                    <div :class="[item.name.length>5? 'resultName' : '']"  ><span class="item-name">{{item.name}}</span></div>
                                    <el-progress style="width:200px;position:absolute;left:148px;transform: translateY(4px);"  :percentage="item.score"></el-progress>
                                  </div>
                              </div>
                          </div>
                        </div>
                    </div>
                </div>
            </div>
            <div class="intro-box">
                <div class="intro_title">
                    <div style="text-align: center;padding-top:8px">
                        <span style="color:#333333;font-size:18px">内容介绍</span>
                    </div>
                    <div class="intro-bg">
                        <div class="resultIntro" v-if="animation">
                          <div v-if="resultIntro !== undefined" style="font-size:18px;color:#000000;">
                            <div class="introTitle">{{introTitle}}</div>
                            <div class="text">
                              {{resultIntro}}
                            </div>
                          </div>
                        </div>
                        <div v-if="resultIntro === undefined && animation" style="position:absolute;left:148px;top:101px">
                          <img src="../../assets/img/empty_intro.png" alt="">
                        </div>
                    </div>
                </div>
            </div>
            <div style="position:absolute;bottom:36px">
                <span style="color:#333333;font-size:14px">注: 识别内容来源于网络，识别结果仅供参考</span>
            </div>
        </div>
    </div>
  </div>
</template>
<script>
import mixin from "../../mixin/mixin";
const axios = require("axios");
import qrCode from "qrcode";
import request from "../../utils/request";
import { StringUtil } from "../../../../../static/utils/StringUtil";
import JSZip, { file } from "jszip";
import {collectUserPoint} from '../../api/point'
export default {
  mixins: [mixin],
  name: "recognize",
  data() {
    return {
      empty:true,//未上传
      qrImage: null,//
      uploadImage:null,//
      ImgUrlBase:'',
      showCode:false,//
      continuePoll:true,//轮询
      uploadByPhone:false,//
      file:file,
      proofImage:null,//
      selectClass:'',//
      checkList:[],
      readPicFlag:'',//
      urlEncode:'',//
      recognizeResult:[],//
      resultIntro:'',//
      scan:false,//扫描动画
      frame:false,//动画框
      animation:false,//动画结束
      introTitle:'',
      lessonId:'',
      outTime:'',
      isDestroy:'',
    };
  },
  watch:{
    abilityId(val){
      console.log(parseInt(val));
      this.abilityId = parseInt(val)
    },
    continuePoll(val){
      console.log(val);
    },
    selectClass(val){
      console.log(val);
    }
  },
  mounted() {
    collectUserPoint({ channel: 12 });
    console.log(this.$route.params);
    this.lessonId = localStorage.recognize_lessonId
    // console.log(this.lessonId);
    // console.log(localStorage);
    this.getAllability();
  },
  methods: {
    //获取识别种类
    getAllability(){
      let params = {};
      request({
        url : "/readPicture/getAllability",
        method:"post",
        data:params,
      }).then(res=>{
        if (res.code === "0") {
          console.log(res);
          this.checkList = res.returnValue
          this.selectClass = this.checkList[0]
        }
      })
    },
    //获取二维码readPicFlag
    postReadPicFlag() {
      let params = {};
      request({
        url: "/readPicture/postReadPicFlag",
        method: "post",
        data: params,
      }).then((res) => {
        if (res.code == "0") {
          console.log(res);
          this.readPicFlag = res.returnValue.readPicFlag
          this.outTime =  res.returnValue.validTime
          this.isDestroy =  res.returnValue.callDeprecated
          console.log(this.isDestroy);
          this.createQrcode(this.readPicFlag);
        }
      });
    },
    //生成二维码
    createQrcode(readPicFlag) {
      let _this = this;
      let env = this.$readIniFile("data", "env");
      let envDomain =
        env === this.$CONST.global.developmentStr
          ? this.$CONST.global.developmentWxDomain
          : this.$CONST.global.productionWxDomain;
      let url = StringUtil.format(
        "https://{0}/h5-image-trans/index.html?readPicFlag={1}#/recognize",
        envDomain,
        readPicFlag
      );
      qrCode.toDataURL(
        url,
        {
          errorCorrectionLevel: "L",
          type: "image/jpeg",
          margin: 0,
          scale: 10,
        },
        function (err, res) {
          if (err) {
            _this.qrImage = "";
          } else {
            _this.qrImage = res;
            _this.timer = setTimeout(() => {
              _this.showCode = false;
              _this.continuePoll = false 
            }, _this.outTime);
          }
        }
      );
      var timer = setInterval(poll,3000)
      function poll(){
        let data = {readPicFlag:readPicFlag};
          request({
            url: "/readPicture/getInfoByReadPicFlag",
            method: "post",
            data: data,
          }).then((res) => {
            console.log(res);
            if (res.code === "0" && res.returnValue.imgUrl) {
              _this.empty = false
              _this.uploadByPhone = true
              _this.uploadImage = res.returnValue.imgUrl
              if (_this.isDestroy === '1') {
                _this.recognizeResult=[];//清空上一张图片识别结果
                _this.resultIntro='';//清空上一张图片识别结果
              }
              _this.introTitle='';
            }
          })
          if (_this.continuePoll === false) {
            clearInterval(timer)
          }
      }
    },
    //二维码失效  
    destroyQrcode(){
      let params = {readPicFlag:this.readPicFlag}
        request({
          url: "/readPicture/deprecatedReadPicFlag",
          method: "post",
          data: params,
        }).then(res=>{
          console.log(res);
        })
    },
    //手机上传
    Telupload(){
        this.showCode = !this.showCode;
        if (this.showCode === false) {
          if (this.isDestroy === '1') {
             this.continuePoll = false
             this.destroyQrcode()
          }
        }else{
          this.continuePoll = true
          this.postReadPicFlag();
        } 
    },
    //本地上传
    localUpload(){
      this.$refs.upImg.clearFiles()
      if (this.readPicFlag !== '') {
        this.destroyQrcode()
        this.showCode = false
        this.continuePoll = false
      }
      
    },
    //展示上传图片
    beforeUpload(file){
      this.uploadImage = file.path
      if (this.uploadImage !== null) {
        this.empty = false
      }
      this.file = file
      this.getBase64(file).then(res => {
        const params = res
        this.proofImage = params
        this.uploadByPhone = false
        this.recognizeResult=[]; //清空上一张图片识别结果
        this.resultIntro=''; //清空上一张图片识别结果
        this.introTitle='';
      })
    },
    //获取图片urlbase64编码
    getUrlBase64(url) {
      return new Promise((resolve, reject) => {
        var Img = new Image()
        var dataURL = ''
        Img.setAttribute('crossOrigin', 'Anonymous')
        Img.src = url + '?v=' + Math.random()
        Img.onload = function() {
          // 要先确保图片完整获取到，这是个异步事件
          var canvas = document.createElement('canvas') // 创建canvas元素
          var width = Img.width // 确保canvas的尺寸和图片一样
          var height = Img.height
          canvas.width = width
          canvas.height = height
          canvas.getContext('2d').drawImage(Img, 0, 0, width, height) // 将图片绘制到canvas中
          dataURL = canvas.toDataURL('image/jpeg') // 转换图片为dataURL
          resolve(dataURL)
        }
      })
    },
    async baseCallback(url) {
      try {
        console.log('执行')
        console.log(url);
        const res = await this.getUrlBase64(url)
        console.log(res) // 获取到结果
        this.ImgUrlBase = res // 我这里将结果赋值给需要用的变量属性
      } catch (err) {
        console.log(err)
      }
    },
    //获取本地base64编码
    getBase64(file) {
      // console.log(file);
      return new Promise(function (resolve, reject) {
        var reader = new FileReader()
        var imgResult = ''
        reader.readAsDataURL(file)
        reader.onload = function () {
          imgResult = reader.result
          let index = imgResult.indexOf('base64')
          let urlEncode = imgResult.slice(index+7,imgResult.length)
          // console.log(urlEncode);
          console.log(index)
          this.urlEncode = encodeURIComponent(urlEncode)
          // console.log(this.urlEncode);
        }
       
        reader.onerror = function (error) {
          reject(error)
        }
        reader.onloadend = function () {
          resolve(imgResult)
        }
      })
    },
    //识别预处理
    handleRecoginze(){
      if (this.empty === true) {
        return
      }
      let _this = this;
      _this.scan = true
      _this.frame = true
      _this.animation = false
      setTimeout(function () {
        _this.scan = false
      },2500)
      setTimeout(function () {
       _this.frame = false
       _this.animation = true
      },2700)
      let data = {
        lessonId:_this.lessonId ? _this.lessonId : "1240973771648540673",
        abilityId:_this.selectClass.id,
      };
      request({
        url : "/readPicture/getReadPicToken",
        method:"post",
        data:data,
      }).then(res=>{
        console.log(res);
        if (res.code === "0") {
          _this.recoginze(res.returnValue.readPicToken)
        }else{
          this.$message.error('识别失败')
        }
      }).catch(err=>{
        this.$message.error('网络异常')
      })
    },
    //识别
    recoginze(readPicToken){
      var _this = this;
      // _this.continuePoll = false  //开始识别后结束轮询
      this.showCode = false
      if (_this.uploadByPhone === true) {//手机上传
        // _this.baseCallback(_this.uploadImage)
        var http = new XMLHttpRequest();	
        var url = _this.selectClass.url+"?access_token=" + readPicToken+'&baike_num=5';
        // var img = 'image=' + this.ImgUrlBase    //
        var img = 'url=' + encodeURIComponent(_this.uploadImage ) 
        http.open("post",url,true);	
	      http.setRequestHeader('content-type','application/x-www-form-urlencoded');			
	      http.send(img);
        http.onreadystatechange = (httpXml)=>{
          if ( httpXml.currentTarget.readyState === 4 && httpXml.currentTarget.status === 200) {
            let response = JSON.parse(httpXml.currentTarget.response) 
            _this.recognizeResult = response.result
            _this.introTitle = _this.recognizeResult[0].name
            _this.resultIntro = response.result[0].baike_info.description
            _this.recognizeResult.forEach(item=>{
              item.score = Number((item.score*100).toFixed(1)) 
            })
            console.log(_this.recognizeResult);
            console.log(_this.resultIntro);
          } 
        }
        if (_this.isDestroy === '1') {
          _this.destroyQrcode()
          _this.continuePoll = false 
        }
        return
      }
        console.log(this.file);
        var reader = new FileReader()
        var imgResult = ''
        reader.readAsDataURL(this.file)
        reader.onload = function () {
        imgResult = reader.result
        let index = imgResult.indexOf('base64')
        let urlEncode = imgResult.slice(index+7,imgResult.length)
        this.urlEncode = encodeURIComponent(urlEncode)  //base64编码转urlEncode编码
        console.log(this.urlEncode);
      
        var http = new XMLHttpRequest();						
	      var url = _this.selectClass.url+"?access_token=" + readPicToken+'&baike_num=5';
        var img = "image="+this.urlEncode;		
	      http.open("post",url,true);	
	      http.setRequestHeader('content-type','application/x-www-form-urlencoded');			
	      http.send(img);
        http.onreadystatechange = (httpXml)=>{
          if ( httpXml.currentTarget.readyState === 4 && httpXml.currentTarget.status ===200) {
            let response = JSON.parse(httpXml.currentTarget.response) 
            // console.log(response); 
            // this.recognizeResult = response.result
            // this.resultIntro = response.result[0].baike_info.descriptionaaaa  //这里的this指向变成了申明对象
            _this.recognizeResult = response.result
            _this.introTitle = _this.recognizeResult[0].name
            _this.resultIntro = response.result[0].baike_info.description
            _this.recognizeResult.forEach(item=>{
              item.score = Number((item.score*100).toFixed(1)) 
            })
            console.log(_this.recognizeResult);
            console.log(_this.resultIntro);
          }
        }
      }
    },
    //窗口最小化
    windowMin() {
      this.$electron.ipcRenderer.send("resource-window-minimize", {
        metaId: 'recognize',
      });
    },
    //关闭窗口
    windowClose() {
      this.destroyQrcode()
      this.continuePoll = false 
      this.$electron.ipcRenderer.send("close-resource-window", {
        metaId: 'recognize',
      });
    },
  },
};
</script>

<style lang="scss" scope>
.el-radio__input.is-checked .el-radio__inner{
       background-color: #fff;
        border-color:#fff ;
     }
 .el-radio{
    opacity:1!important;
    color: #fff!important;
    .el-radio__input.is-checked+.el-radio__label {
      color: #fff;
    }
    .el-radio__input{
      // display: none;
      .el-radio__inner{
        border:1.5px solid #fff;
        border-radius: 100%;
        width: 16px;
        height: 16px;
        background-color:transparent;
        cursor: pointer;
        -webkit-box-sizing: border-box;
        box-sizing: border-box;
      }
      &.is-checked{
      position: relative;
      .el-radio__inner{
      //  background-color: rgb(136, 134, 134);
       border: 1.5px solid #eeeeee;
        background: #fff;
        width: 16px;
        height: 16px;
      }
      &.el-radio__label {
       color: #fff;
     }
    }
    }
    
  }
  .el-progress__text{
    position: relative;
    left:30px;
  }
</style>
<style lang="scss" scoped>
.container {
  width: 100%;
  min-height: 100vh;
  // background-color: #fff;
  background-image: url("../../assets/img/recognize_bg.png");
  background-repeat: no-repeat;
  background-size: cover;
  .title-wrap {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 64px;
    background-image: url("../../assets/img/title_bg.png");
    background-size: cover;
    -webkit-app-region: drag;
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 0 30px;
    box-sizing: border-box;
    z-index: 98;

    .title-text {
      display: flex;
      align-items: center;
      img {
        margin-right: 8px;
        width: 20px;
        height: 20px;
      }
      span {
        font-size: 18px;
        color: #fff;
      }
    }

    .title-btns {
      -webkit-app-region: no-drag;
      img {
        width: 14px;
        height: 14px;
        margin-left: 18px;
        cursor: pointer;
      }
    }
  }
  .content {
    display: flex;
    height: calc(100vh - 64px);
    .left_wrap{
        width: 61%;
        padding-left:69px ;
        padding-right:69px ;
        position: relative;
        .frame{
          width: 731px;
          height: 445px;
          background-image: url("../../assets/img/frame.png");
          background-repeat: no-repeat;
          background-size: cover;
          position: absolute;
          z-index: 999px;
          top: 180px;
          right:69px;
        }
        .img_mask{
          width: 726px;
          height: 445px;
          position: absolute;
          border-radius: 4px;
          top: 182px;
          right:72px;
          z-index: 99;
          background: 
	        linear-gradient(#ccf0ff, #ccf0ff),
	        linear-gradient(90deg, #ffffff33 1.5px,transparent 0,transparent 19px),
	        linear-gradient( #ffffff33 1.5px,transparent 0,transparent 19px),
	        linear-gradient(transparent, #6cd6ff);
	        background-size:100% 3px, 10% 100%,100% 8%, 100% 100%;
	        background-repeat:no-repeat, repeat, repeat, no-repeat;
	        background-position: 0% 0%, 0 0, 0 0, 0 0;
	        /* 初始位置 */
	        clip-path: polygon(0% 0%, 100% 0%, 100% 1.5%, 0% 1.5%);
	        /* 添加动画效果 */
	        animation: move 2.5s infinite linear;
        }
        .img_container{
            margin: 45px 0 0 0;
            width: 751px;
            height: 465px;
            border-radius: 8px;
            position: relative;
            text-align: center;
            display: flex;
            justify-content: center;
            align-items: center;
            .empty_img{
                width: 369px;
                height: 356px;
                transform: translateY(-30px);
            }
            .uploadImage{
              max-width: 751px;
              max-height: 462px;
              border-radius: 4px;
              transform: translateY(-2px);
            }
            .select_box{
                position: absolute;
                bottom: 21px;
                left: 184px;
                width: 381px;
                height: 41px;
                border-radius: 20.5px;
                z-index: 999;
                background-color: #0085FF;
                opacity: 0.55;
                color: #fff;
                display: flex;
                justify-content: center;
                
            }
            .checkList{
                  // padding: 8px 20px 0px 20px;
                  border-radius: 20.5px;
                  border: none;
                  width: 381px;
                  height: 41px;
                  position: absolute;
                  bottom: 20px;
                  z-index: 999;
                  display: flex;
                  justify-content: center;
            }
        }
        .qrcode-box{
            width: 136px;
            height: 181px;
            position: absolute;
             top: -90px;
            border-radius: 20px 20px 30px 30px;
            border:3px solid #0078FE;
            border-bottom:none;
            padding-bottom: 32px;
            background-color: #fff;
            display: flex;
            justify-content: center;
            align-items: center;
            flex-direction: column;
            z-index: 99;
            img{
                width: 107px;
                height: 107px;
                border-radius: 4px;
            }
        }
        .btn_wrap{
            width: 751px;
            margin-top: 50px;
            // margin-left:20px ;
            display: flex;
            position: relative;
        }
        .up_btn{
            width: 136px;
            height: 41px;
            background-color: #0078FE;
            color: #fff;
            font-size: 14px;
            // margin-right:40px;
           
            z-index: 99;
            cursor: pointer;
        }
        .recognize{
            width: 136px;
            height: 41px;
            border-radius: 30px;
            color: #fff;
            background-color: #F89723;
            font-size: 14px;
            position: absolute;
            right: 0px;
            cursor: pointer;
        }
    }
    
    .right_wrap{
        width: 39%;
        padding: 72px 46px 0 46px;
        .result-box{
            width: 471px;
            .result_title{
                width: 471px;
                height: 41px;
                background-color: #D9EDFF;
                border-radius: 4px;
                .result-bg{
                    margin-top: 15px;
                    border-radius: 4px;
                    width: 471px;
                    height: 142px;
                    background-image: url("../../assets/img/resultBackground.png");
                    background-repeat: no-repeat;
                    background-size: cover;                  
                }
                .recognizeResult{
                  width:471px;
                  height:140px;
                  overflow-y: scroll;
                }
                 .recognizeResults{
                  width:471px;
                  height:120px;
                  overflow-y: scroll;
                }
                .resultName {
                //  width: 108px;
                 display: inline-flex;
                 overflow-x: hidden;
                }
                .item-name{
                  cursor: pointer;
                  width: 108px;
                  white-space: nowrap;
                  overflow: hidden;
                  text-overflow:ellipsis;
                }
                .resultName .item-name:hover{
                  // width: 270px;
                  display: block;
                  z-index:999;
                  animation: textFlow 3s 0.3s linear infinite;
                  text-overflow:inherit;
                }
                @keyframes textFlow {
                  to {
                    transform: translate3d(-200%, 0, 0);
                  }
                }
            }
        }
        .intro-box{
            width: 471px;
            margin-top: 150px;
            .intro_title{
                width: 471px;
                height: 41px;
                background-color: #D9EDFF;
                border-radius: 4px;
            }
            .intro-bg{
                margin-top: 15px;
                border-radius: 4px;
                width: 471px;
                height: 447px;
                background-image: url("../../assets/img/introBackground.png");
                background-repeat: no-repeat;
                background-size: cover;
                position: relative;
            }
            .resultIntro{
                text-align: justify;
                padding: 20px 32px 20px 5px;
                margin: 10px 35px;
                width: 435px;
                height: 390px;
                color: #333333;
                // text-indent: 2em;
                position: relative;
                overflow-y: scroll;
                cursor: pointer;
            }
            .introTitle{
              text-align: left;
              width: 402px;
              height: 31px;
              padding: 8px 0 5px 5px;
            }
            .text{
              font-size: 16px;
              line-height: 30px;
              word-spacing: 2px;
              padding: 0px 6px 0 5px;
            }
        }
    }
    @keyframes move{
    	to{
    		/* 终止位置 */
    	}
      50%{
        background-position: 0 100%,0 0, 0 0, 0 0;
        clip-path: polygon(0% 0%, 100% 0%, 100% 100%, 0% 100%);
      }
      100%{
        background-position: 0 0,0 0, 0 0, 0 0;
        clip-path: polygon(0% 0%, 100% 0%, 100% 1.5%, 0% 1.5%);
      }
    }
  }
}
</style>
